import { Component, Inject, Prop, Vue } from 'vue-property-decorator'
import DataModel from '../data-model/data-model.vue'
import Cell from '../cell/cell'
import SearchItem from '../search-item/search-item.vue'

@Component({ components: { DataModel, Cell, SearchItem } })
export default class extends Vue {
  // ++++++++++ model ++++++++++
  dataVisible = false
  isAdd = false

  // ++++++++++ props ++++++++++
  @Prop({ default: () => ([]) })
  data!: Array<any>

  @Prop()
  columns!: Array<IColumn>

  @Prop({ default: () => ({ total: 0, page: 1, pageSize: 10 }) })
  pagination!: { total: number, page: number, pageSize: number }

  @Prop({ default: false })
  loading!: boolean

  @Prop({ default: '添加' })
  addTitle!: string

  @Prop({ default: '' })
  btns!: string

  // ++++++++++ data ++++++++++
  // ++++++++++ computed ++++++++++
  @Inject('dataProvide') dataProvide!: () => any

  get selection(): Array<any> {
    return this.dataProvide().selection
  }

  // ++++++++++ methods normal ++++++++++
  handleShowTable(column: IColumn) {
    if (column.isShowTable === undefined) {
      return true
    }
    if (!column.isShowTable) {
      return false
    }
    return true
  }

  isShowBtn(value: string) {
    let btns = this.btns.split(',')

    btns = btns.map(item => item.trim())
    return btns.includes(value)
  }

  formatData(row: any, column: IColumn) {
    let key = column.key
    let value = row[column.key]

    if (column.format) {
      row[key] = value
      value = column.format(row)
    }
    return value ?? '-'
  }

  formatRender(column: IColumn) {
    if (column.render) {
      return column.render
    }
    return (h: any, { data }: any) => h('span', data)
  }

  /** 页码变化时 */
  onCurrentChange(_page: number) {
    const { total, pageSize } = this.pagination

    this.$emit('update:pagination', { total, page: _page, pageSize })
  }

  /** 选着变化时 */
  onSelectionChange(selection: Array<any>) {
    this.dataProvide().selection = selection
  }

  // ++++++++++ methods event ++++++++++
  /** 某一行被点击时 */
  handleRowClick(row: number) {
    const dataTable = this.$refs.dataTable as any

    dataTable.clearSelection()
    dataTable.toggleRowSelection(row)
  }

  /** 刷新 */
  handleRefresh() {
    this.dataProvide().handleRefresh()
  }

  /** 编辑数据 */
  handleEdit() {
    this.isAdd = false
    this.dataVisible = true
  }

  /** 添加数据 */
  handleAdd() {
    this.isAdd = true
    this.dataVisible = true
  }

  /** 删除数据 */
  handleRemove() {
    // const ids = this.selection.map(item => item.id)
    this.dataProvide().handleRemove({ id: this.selection[0].id })
  }

  // ++++++++++ Lifecycle Hooks ++++++++++
  // ++++++++++ watch ++++++++++
}
